package com.example.administrator.energyida.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.energyida.R;
import com.example.administrator.energyida.adapter.ItemExpandableFactoryAdapter;
import com.example.administrator.energyida.adapter.ItemExpandableListAdapter;
import com.example.administrator.energyida.beans.FactoryBean;
import com.example.administrator.energyida.beans.WorkshopBean;
import com.example.administrator.energyida.util.OceanUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FactoryListActivity extends Activity implements ItemExpandableListAdapter.Callback {

    private TextView buttonBack;
    private ExpandableListView listView;

    private String email;
    private String getFactoryResponse;
    private String getWorkshopResponse;

    private String fName;
    private String wName;
    private String wChargeName;
    private String wChargePhone;
    private String wChargeInfo;
    private String wUseWater;
    private String wUseElectricity;
    private String wUseGas;
    private String wUseHeat;
    private String addMode;

    private String wResponse;

    private ArrayList<HashMap<String, String>> factoryList = new ArrayList<>();
    private ArrayList<ArrayList<HashMap<String, String>>> workshopList = new ArrayList<>();
    private List<FactoryBean.ContentBean> factoryBeanList = new ArrayList<>();
    private List<List<WorkshopBean.ContentBean>> workshopBeanList = new ArrayList<>();

    Handler handler;
    ItemExpandableListAdapter adapter;
    private QMUITipDialog qmuiTipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factory_list);

        initView();
        initHandler();
        initExpandableListView();

        buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String wId = workshopBeanList.get(groupPosition).get(childPosition).getWId();
                String wMode = workshopBeanList.get(groupPosition).get(childPosition).getMode();

                if (wMode.equals("0")) {
                    Toast.makeText(FactoryListActivity.this, "云端数据", Toast.LENGTH_SHORT).show();
                    return false;
                }

                Intent intent = new Intent(FactoryListActivity.this, ManualAddActivity.class);
                intent.putExtra("wId", wId);
                intent.putExtra("useWater", workshopBeanList.get(groupPosition).get(childPosition).getWWater());
                intent.putExtra("useElectricity", workshopBeanList.get(groupPosition).get(childPosition).getWElectricity());
                intent.putExtra("useGas", workshopBeanList.get(groupPosition).get(childPosition).getWGas());
                intent.putExtra("useHeat", workshopBeanList.get(groupPosition).get(childPosition).getWHeat());
                startActivity(intent);
                return false;
            }
        });
    }

    private void initExpandableListView() {
        adapter = new ItemExpandableListAdapter(factoryList, workshopList, FactoryListActivity.this, this);
        listView.setAdapter(adapter);
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        if (getFactoryResponse.contains("10007")) {
                            Gson gsonFactory = new Gson();
                            FactoryBean factoryBean = gsonFactory.fromJson(getFactoryResponse, FactoryBean.class);
                            factoryBeanList = factoryBean.getContent();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < factoryBeanList.size(); i++) {
                                        String fId = factoryBeanList.get(i).getFId();
                                        String fName = factoryBeanList.get(i).getFName();
                                        String fManager = factoryBeanList.get(i).getFManager();
                                        String fPhone = factoryBeanList.get(i).getFPhone();


                                        HashMap<String, String> hashMap = new HashMap<>();
                                        hashMap.put("fName", fName);

                                        factoryList.add(hashMap);

                                        JSONObject jsonObject = new JSONObject();
                                        try {
                                            jsonObject.put("email", email);
                                            jsonObject.put("mode", 3);
                                            jsonObject.put("factory", fId);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                        new OceanUtil("getAccountAllInfo.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                                            @Override
                                            public void callback(String strResponse) {
                                                Gson gson = new Gson();
                                                WorkshopBean workshopBean = gson.fromJson(strResponse, WorkshopBean.class);
                                                workshopBeanList.add(workshopBean.getContent());
                                            }
                                        }).AsynPostInfo();

                                    }

                                    Message message = new Message();
                                    message.what = 2;
                                    handler.sendMessage(message);
                                }
                            }).start();

                        }
                        if (getFactoryResponse.contains("-20007")) {
                            Toast.makeText(FactoryListActivity.this, "获取列表失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 2:
                        for (int i = 0; i < workshopBeanList.size(); i++) {
                            ArrayList<HashMap<String, String>> child = new ArrayList<>();
                            for (int j = 0; j < workshopBeanList.get(i).size(); j++) {
                                String wName = workshopBeanList.get(i).get(j).getWName();
                                String wMode = workshopBeanList.get(i).get(j).getMode();
                                HashMap<String, String> hashMap = new HashMap<>();

                                hashMap.put("wName", wName);
                                hashMap.put("wMode", wMode);

                                child.add(hashMap);
                            }
                            workshopList.add(child);
                        }
                        adapter.notifyDataSetChanged();
                        qmuiTipDialog.dismiss();
                        break;
                    case 3:
                        qmuiTipDialog.dismiss();
                        if (wResponse.contains("10021")) {
                            Toast.makeText(FactoryListActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            getData();
                        }
                        if (wResponse.contains("-20021")) {
                            Toast.makeText(FactoryListActivity.this, "车间修改失败", Toast.LENGTH_SHORT).show();
                        }

                        break;
                    default :
                        break;
                }
            }
        };
    }

    private void getData() {
        factoryBeanList.clear();
        factoryList.clear();
        workshopBeanList.clear();
        workshopList.clear();

        JSONObject getFactory = new JSONObject();
        try {
            getFactory.put("email", email);
            getFactory.put("mode", 2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        qmuiTipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create();
        qmuiTipDialog.show();

        new OceanUtil("getAccountAllInfo.php", getFactory, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                getFactoryResponse = strResponse;
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }).postInfo();
    }

    private void initView() {
        // 设置状态栏的颜色
        StatusBarUtil.setColor(FactoryListActivity.this, Color.parseColor("#10cafd"), 50);

        buttonBack = findViewById(R.id.text_factoryList_back);
        listView = findViewById(R.id.listView_factoryList);

        //获取数据并展示
        SharedPreferences sharedPreferences = getSharedPreferences("account", MODE_PRIVATE);
        email = sharedPreferences.getString("email", "");

        getData();
    }

    @Override
    public void click(View view) {
        int groupPosition = (int) view.getTag(R.id.groupTag);
        int childPosition = (int) view.getTag(R.id.childTag);

        switch (view.getId()) {
            case R.id.factory_imageView_editFarm:
                break;
            case R.id.factory_switch_manual:
                boolean isChecked = (boolean) view.getTag(R.id.switchTag);
                if (isChecked) {
                    addMode = "0";
                } else {
                    addMode = "1";
                }

                fName = factoryBeanList.get(groupPosition).getFName();
                wName = workshopBeanList.get(groupPosition).get(childPosition).getWName();
                wChargePhone = workshopBeanList.get(groupPosition).get(childPosition).getWPhone();
                wChargeName = workshopBeanList.get(groupPosition).get(childPosition).getWManager();
                wUseWater = workshopBeanList.get(groupPosition).get(childPosition).getWWater();
                wUseElectricity = workshopBeanList.get(groupPosition).get(childPosition).getWElectricity();
                wUseGas = workshopBeanList.get(groupPosition).get(childPosition).getWGas();
                wUseHeat = workshopBeanList.get(groupPosition).get(childPosition).getWHeat();

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("email", email);
                    jsonObject.put("fName", fName);
                    jsonObject.put("oldName", wName);
                    jsonObject.put("newName", wName);
                    jsonObject.put("wPhone", Long.parseLong(wChargePhone));
                    jsonObject.put("wManager", wChargeName);
                    jsonObject.put("wWater", Integer.parseInt(wUseWater));
                    jsonObject.put("wElectricity", Integer.parseInt(wUseElectricity));
                    jsonObject.put("wGas", Integer.parseInt(wUseGas));
                    jsonObject.put("wHeat", Integer.parseInt(wUseHeat));
                    jsonObject.put("wMode", addMode);
                    jsonObject.put("mode", 2);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                qmuiTipDialog = new QMUITipDialog.Builder(this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                        .setTipWord("正在加载")
                        .create();
                qmuiTipDialog.show();

                new OceanUtil("resetWorkshop.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                    @Override
                    public void callback(String strResponse) {
                        wResponse = strResponse;
                        Message message = new Message();
                        message.what = 3;
                        handler.sendMessage(message);
                    }
                }).postInfo();
            break;
        }
    }
}
